/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package domain.service.impl;

import domain.domain.MyUser;
import me.zhengjie.exception.EntityExistException;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import domain.repository.MyUserRepository;
import domain.service.MyUserService;
import domain.service.dto.MyUserDto;
import domain.service.dto.MyUserQueryCriteria;
import domain.service.mapstruct.MyUserMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author ljj
* @date 2021-02-07
**/
@Service
@RequiredArgsConstructor
public class MyUserServiceImpl implements MyUserService {

    private final MyUserRepository myUserRepository;
    private final MyUserMapper myUserMapper;

    @Override
    public Map<String,Object> queryAll(MyUserQueryCriteria criteria, Pageable pageable){
        Page<MyUser> page = myUserRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(myUserMapper::toDto));
    }

    @Override
    public List<MyUserDto> queryAll(MyUserQueryCriteria criteria){
        return myUserMapper.toDto(myUserRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public MyUserDto findById(Long userId) {
        MyUser myUser = myUserRepository.findById(userId).orElseGet(MyUser::new);
        ValidationUtil.isNull(myUser.getUserId(),"MyUser","userId",userId);
        return myUserMapper.toDto(myUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MyUserDto create(MyUser resources) {
        if(myUserRepository.findByUsername(resources.getUsername()) != null){
            throw new EntityExistException(MyUser.class,"username",resources.getUsername());
        }
        if(myUserRepository.findByEmail(resources.getEmail()) != null){
            throw new EntityExistException(MyUser.class,"email",resources.getEmail());
        }
        return myUserMapper.toDto(myUserRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(MyUser resources) {
        MyUser myUser = myUserRepository.findById(resources.getUserId()).orElseGet(MyUser::new);
        ValidationUtil.isNull( myUser.getUserId(),"MyUser","id",resources.getUserId());
        MyUser myUser1 = null;
        myUser1 = myUserRepository.findByUsername(resources.getUsername());
        if(myUser1 != null && !myUser1.getUserId().equals(myUser.getUserId())){
            throw new EntityExistException(MyUser.class,"username",resources.getUsername());
        }
        myUser1 = myUserRepository.findByEmail(resources.getEmail());
        if(myUser1 != null && !myUser1.getUserId().equals(myUser.getUserId())){
            throw new EntityExistException(MyUser.class,"email",resources.getEmail());
        }
        myUser.copy(resources);
        myUserRepository.save(myUser);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long userId : ids) {
            myUserRepository.deleteById(userId);
        }
    }

    @Override
    public void download(List<MyUserDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (MyUserDto myUser : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("用户名", myUser.getUsername());
            map.put("昵称", myUser.getNickName());
            map.put("性别", myUser.getGender());
            map.put("手机号码", myUser.getPhone());
            map.put("邮箱", myUser.getEmail());
            map.put("头像地址", myUser.getAvatarName());
            map.put("头像真实路径", myUser.getAvatarPath());
            map.put("密码", myUser.getPassword());
            map.put("是否为admin账号", myUser.getIsAdmin());
            map.put("状态：1启用、0禁用", myUser.getEnabled());
            map.put("创建者", myUser.getCreateBy());
            map.put("更新着", myUser.getUpdateBy());
            map.put("修改密码的时间", myUser.getPwdResetTime());
            map.put("创建日期", myUser.getCreateTime());
            map.put("更新时间", myUser.getUpdateTime());
            map.put("工号", myUser.getNu());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}